package com.zeny.coding.controller.admin.file;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetMezzanineInfoResponse;

import com.zeny.coding.config.OssConfig;
import com.zeny.coding.config.VodConfig;
import com.zeny.coding.constants.CourseConstants;
import com.zeny.coding.dto.FileDto;
import com.zeny.coding.dto.PageDto;
import com.zeny.coding.dto.Response;
import com.zeny.coding.service.FileService;
import com.zeny.coding.util.DeleteFileUtil;
import com.zeny.coding.util.VodUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <h2>文件</h2>
 *
 * @Author Zeny
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/file/admin/file")
@Slf4j
public class FileController {

    @Autowired
    private OssConfig ossConfig;

    @Autowired
    private VodConfig vodConfig;

    @Autowired
    private FileService fileService;

    @Autowired
    private DeleteFileUtil deleteFileUtil;

    @PostMapping("/list")
    public Response list(@RequestBody PageDto<FileDto> pageDto) {
        pageDto.check();
        fileService.list(pageDto);
        return new Response().success().data(pageDto).message(CourseConstants.QUERY_SUCCESS);
    }

    /**
     * <h2>文件的绝对路径</h2>
     * @param null
     **/
    @Value("${file.path}")
    private String path;

    @PostMapping("/delete")
    public Response deleteByFileName(@RequestBody FileDto fileDto) throws Exception {
        fileDto.validForDelete();
        this.fileService.deleteById(fileDto.getId());
        deleteFileUtil.delete(fileDto);
        return new Response().success().message(CourseConstants.DELETE_SUCCESS);
    }

    /**
     * <h2>检查文件分片</h2>
     * @param key
     **/
    @GetMapping("/check/{key}")
    public Response check(@PathVariable("key") String key) throws Exception{
        log.info("检查上传分片开始: {}", key);
        FileDto fileDto = fileService.findByKey(key);
        if (fileDto != null) {
            if (StringUtils.isEmpty(fileDto.getVod())) {
                //使用的是oss存储图片之类
                fileDto.setPath(ossConfig.getDomain() + fileDto.getPath());
            } else {
                //使用视频点播
                DefaultAcsClient vodClient = VodUtil.initVodClient(vodConfig.getAccessKeyId(), vodConfig.getAccessKeySecret());
                GetMezzanineInfoResponse response = VodUtil.getMezzanineInfo(vodClient, fileDto.getVod());
                log.info("获取视频信息, response: {}", response);
                //获取播放地址
                String fileURL = response.getMezzanine().getFileURL();
                fileDto.setPath(fileURL);
            }
        }
        return new Response().success().data(fileDto);
    }

}
